#pragma once

#include "Utils.cpp"
#include "EventLoop.cpp"
#include "VideoStateEnum.cpp"
#include "ThreadPool.cpp"
#include "ThreadQueue.cpp"

#include <memory>
#include <atomic>
#include <deque>
#include <future>

extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <jni.h>
#include <log/log.h>
}

using namespace std::chrono;

class PlayerBase {
public:
    std::atomic_bool active{false};

    //恢复播放
    virtual void resumePlay() = 0;

    //暂停播放
    virtual void pausePlay() = 0;

protected:
    ThreadPool pool;//线程池
    EventLoop loop;//时间循环

    std::atomic_int errCount{0};//错误次数
    const int retryCount{10};//能重试次数

    std::mutex stateMutex;//状态锁
    VideoStateEnum videoState{VideoStateEnum::destroy};
    VideoStateEnum pendingState{VideoStateEnum::resume};

    //读取
    virtual void read() = 0;

    //解码
    virtual void decode() = 0;

    //渲染
    virtual void renderer() = 0;

    //初始化上下文
    virtual bool initContext()= 0;

    //释放资源
    virtual void releaseContext() = 0;

    //创建一个自动销毁的AvFrame
    inline auto getFrame(bool autoDestroyBuffer = false) {
        return std::shared_ptr<AVFrame>{
                av_frame_alloc(), [=](AVFrame *frame) {
                    if (autoDestroyBuffer) av_free(*frame->extended_data);
                    av_frame_unref(frame);
                    av_frame_free(&frame);
                }
        };
    }

    //设置状态
    void setState(VideoStateEnum newState) {
        if (videoState != newState) {
            videoState = newState;
            if (active.load()) replayPlayStatus(newState);
        }
    }
};